package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.query.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IEmployeeService employeeService;


    @RequiresPermissions(value = {"notice:list", "公告通知页面"}, logical = Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        PageInfo<Notice> pageInfo = noticeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "notice/list";
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"notice:delete", "公告通知删除"}, logical = Logical.OR)
    @ResponseBody
    public JsonResult delete(Long id) {
        if (id != null) {
            noticeService.delete(id);
        }
        return new JsonResult();
    }


    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"notice:saveOrUpdate", "公告通知新增/编辑"}, logical = Logical.OR)
    @ResponseBody
    public JsonResult saveOrUpdate(Notice notice) {
        if (notice.getId() != null) {
            noticeService.update(notice);
        } else {
            noticeService.save(notice);
        }
        return new JsonResult();
    }

    @RequestMapping("/show")
    public String show(Model model, Long id) {
        //根据当前id查询对应的公告信息
        Notice notice = noticeService.get(id);
        //同时将未读状态 改为已读状态
        notice.setRead(true);
        if (notice != null) {
            //先去数据库中查询当前登录用户是否已读这条公告
            //获取当前登录用户的id
            Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
            Notice noticeEmp = noticeService.selectByEmpId(notice.getId(),employee.getId());
            //判断noticeEmp是否为空
            if (noticeEmp == null) {
                //说明数据库中的中间表中这条公告还没有被当前用户读,则应添加关系
                noticeService.insertRelation(notice.getId(),employee.getId());
            }


        }
        //将查询的对象共享至页面
        model.addAttribute("notice", notice);
        return "notice/show";
    }
}
